import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  TextField,
  Button,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  CircularProgress,
  Alert,
  Paper,
  Chip,
  FormControlLabel,
  Checkbox,
  FormGroup
} from '@mui/material';
import {
  Add as AddIcon,
  LocalShipping as CarIcon,
} from '@mui/icons-material';
import { apiRequest } from '../utils/api';

const AddVehicle = () => {
  const [formData, setFormData] = useState({
    // 基本信息
    brand: '',
    model: '',
    year: new Date().getFullYear(),
    licensePlate: '',
    vin: '',
    color: '',
    fuelType: 'GASOLINE',
    transmissionType: 'AUTOMATIC',
    engineCapacity: 2.0,
    vehicleType: 'SEDAN',
    
    // 状态信息
    mileage: 0,
    registrationDate: new Date().toISOString().split('T')[0],
    insuranceExpiry: new Date(new Date().setFullYear(new Date().getFullYear() + 1)).toISOString().split('T')[0],
    lastMaintenance: new Date().toISOString().split('T')[0],
    nextMaintenanceDate: new Date(new Date().setMonth(new Date().getMonth() + 6)).toISOString().split('T')[0],
    
    // 车主信息
    ownerName: '',
    ownerPhone: '',
    ownerEmail: '',
    
    // 设备信息
    deviceId: '',
    deviceSerialNumber: '',
    deviceModel: '',
    deviceVersion: '1.0.0',
    
    // 证件信息
    registrationNumber: '',
    insurancePolicyNumber: '',
    
    // 位置信息
    lastLatitude: 39.9042,
    lastLongitude: 116.4074,
    
    // 安全设备
    hasGPS: true,
    hasAlarm: true,
    hasImmobilizer: false,
    hasCamera: false,
    
    // 其他
    tags: [],
    notes: '',
    status: 'ACTIVE'
  });
  
  const [tagInput, setTagInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);

  // 获取认证token
  const getAuthHeader = () => {
    const token = localStorage.getItem('token');
    return token ? { Authorization: `Bearer ${token}` } : {};
  };

  // 初始化并获取当前用户信息
  useEffect(() => {
    // 获取当前用户信息
    const fetchCurrentUser = async () => {
      try {
        const userResponse = await apiRequest.get('/api/auth/me');
        setCurrentUser(userResponse.data);
      } catch (err) {
        console.error('Error fetching current user:', err);
      }
    };
    
    fetchCurrentUser();
  }, []);

  // 选项常量
  const fuelTypes = [
    { value: 'GASOLINE', label: '汽油' },
    { value: 'DIESEL', label: '柴油' },
    { value: 'ELECTRIC', label: '电动' },
    { value: 'HYBRID', label: '混动' },
    { value: 'LPG', label: '液化石油气' },
    { value: 'CNG', label: '压缩天然气' }
  ];

  const transmissionTypes = [
    { value: 'MANUAL', label: '手动' },
    { value: 'AUTOMATIC', label: '自动' },
    { value: 'CVT', label: '无级变速' },
    { value: 'DCT', label: '双离合' },
    { value: 'AMT', label: '机械式自动' }
  ];

  const vehicleTypes = [
    { value: 'SEDAN', label: '轿车' },
    { value: 'SUV', label: 'SUV' },
    { value: 'MPV', label: 'MPV' },
    { value: 'HATCHBACK', label: '两厢车' },
    { value: 'COUPE', label: '跑车' },
    { value: 'PICKUP', label: '皮卡' },
    { value: 'VAN', label: '厢式货车' }
  ];

  const statuses = [
    { value: 'ACTIVE', label: '正常激活' },
    { value: 'INACTIVE', label: '未激活' },
    { value: 'MAINTENANCE', label: '维修保养中' },
    { value: 'STOLEN', label: '被盗' },
    { value: 'SOLD', label: '已出售' },
    { value: 'SCRAPPED', label: '已报废' }
  ];

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : type === 'number' ? Number(value) : value
    }));
  };

  const handleTagAdd = () => {
    if (tagInput.trim() && !formData.tags.includes(tagInput.trim())) {
      setFormData(prev => ({
        ...prev,
        tags: [...prev.tags, tagInput.trim()]
      }));
      setTagInput('');
    }
  };

  const handleTagDelete = (tagToDelete) => {
    setFormData(prev => ({
      ...prev,
      tags: prev.tags.filter(tag => tag !== tagToDelete)
    }));
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleTagAdd();
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setSuccess(false);

    try {
      // 为日期字段添加默认时间（12:00:00）和时区信息
      const prepareDateWithTime = (dateString) => {
        if (!dateString) return null;
        // 创建Date对象以获取正确的带时区的ISO格式
        const date = new Date(dateString);
        // 设置时间为中午12点
        date.setHours(12, 0, 0, 0);
        // 返回完整的带时区的ISO字符串
        return date.toISOString();
      };
      
      // 转换日期字段为ISO格式（包含时间）
      const submitData = {
        ...formData,
        registrationDate: prepareDateWithTime(formData.registrationDate),
        insuranceExpiry: prepareDateWithTime(formData.insuranceExpiry),
        lastMaintenance: prepareDateWithTime(formData.lastMaintenance),
        nextMaintenanceDate: prepareDateWithTime(formData.nextMaintenanceDate),
        // 自动设置车主信息
        ownerId: currentUser?.id || '',
        ownerName: currentUser?.firstName + ' ' + currentUser?.lastName || '',
        ownerEmail: currentUser?.email || ''
      };

      const response = await apiRequest.post('/api/vehicles', submitData);

      setSuccess(true);
      setFormData({
        brand: '',
        model: '',
        year: new Date().getFullYear(),
        licensePlate: '',
        vin: '',
        color: '',
        fuelType: 'GASOLINE',
        transmissionType: 'AUTOMATIC',
        engineCapacity: 2.0,
        vehicleType: 'SEDAN',
        mileage: 0,
        registrationDate: new Date().toISOString().split('T')[0],
        insuranceExpiry: new Date(new Date().setFullYear(new Date().getFullYear() + 1)).toISOString().split('T')[0],
        lastMaintenance: new Date().toISOString().split('T')[0],
        nextMaintenanceDate: new Date(new Date().setMonth(new Date().getMonth() + 6)).toISOString().split('T')[0],
        ownerName: '',
        ownerPhone: '',
        ownerEmail: '',
        deviceId: '',
        deviceSerialNumber: '',
        deviceModel: '',
        deviceVersion: '1.0.0',
        registrationNumber: '',
        insurancePolicyNumber: '',
        lastLatitude: 39.9042,
        lastLongitude: 116.4074,
        hasGPS: true,
        hasAlarm: true,
        hasImmobilizer: false,
        hasCamera: false,
        tags: [],
        notes: '',
        status: 'ACTIVE'
      });

      // 3秒后隐藏成功消息
      setTimeout(() => setSuccess(false), 3000);
    } catch (err) {
      setError(err.response?.data?.message || '添加车辆失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box p={3}>
      <Typography variant="h4" gutterBottom>
        添加车辆信息
      </Typography>

      <Grid container spacing={3}>
        <Grid item xs={12} md={8}>
          <Card>
            <CardContent>
              {error && (
                <Alert severity="error" sx={{ mb: 2 }}>
                  {error}
                </Alert>
              )}
              
              {success && (
                <Alert severity="success" sx={{ mb: 2 }}>
                  车辆添加成功！
                </Alert>
              )}

              <form onSubmit={handleSubmit}>
                {/* 基本信息 */}
                <Typography variant="h6" gutterBottom sx={{ mt: 2, mb: 1 }}>
                  基本信息
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="品牌"
                      name="brand"
                      value={formData.brand}
                      onChange={handleChange}
                      required
                      variant="outlined"
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="型号"
                      name="model"
                      value={formData.model}
                      onChange={handleChange}
                      required
                      variant="outlined"
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="年份"
                      name="year"
                      type="number"
                      value={formData.year}
                      onChange={handleChange}
                      required
                      variant="outlined"
                      inputProps={{ min: 1900, max: new Date().getFullYear() + 1 }}
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="车牌号"
                      name="licensePlate"
                      value={formData.licensePlate}
                      onChange={handleChange}
                      required
                      variant="outlined"
                      inputProps={{ maxLength: 10 }}
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="VIN码"
                      name="vin"
                      value={formData.vin}
                      onChange={handleChange}
                      required
                      variant="outlined"
                      inputProps={{ maxLength: 17 }}
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="颜色"
                      name="color"
                      value={formData.color}
                      onChange={handleChange}
                      required
                      variant="outlined"
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={4}>
                    <FormControl fullWidth>
                      <InputLabel>燃料类型</InputLabel>
                      <Select
                        name="fuelType"
                        value={formData.fuelType}
                        onChange={handleChange}
                        label="燃料类型"
                      >
                        {fuelTypes.map(type => (
                          <MenuItem key={type.value} value={type.value}>{type.label}</MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  </Grid>
                  
                  <Grid item xs={12} sm={4}>
                    <FormControl fullWidth>
                      <InputLabel>变速箱类型</InputLabel>
                      <Select
                        name="transmissionType"
                        value={formData.transmissionType}
                        onChange={handleChange}
                        label="变速箱类型"
                      >
                        {transmissionTypes.map(type => (
                          <MenuItem key={type.value} value={type.value}>{type.label}</MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  </Grid>
                  
                  <Grid item xs={12} sm={4}>
                    <FormControl fullWidth>
                      <InputLabel>车辆类型</InputLabel>
                      <Select
                        name="vehicleType"
                        value={formData.vehicleType}
                        onChange={handleChange}
                        label="车辆类型"
                      >
                        {vehicleTypes.map(type => (
                          <MenuItem key={type.value} value={type.value}>{type.label}</MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="发动机排量 (升)"
                      name="engineCapacity"
                      type="number"
                      value={formData.engineCapacity}
                      onChange={handleChange}
                      required
                      variant="outlined"
                      inputProps={{ min: 0, max: 10, step: 0.1 }}
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="当前里程 (公里)"
                      name="mileage"
                      type="number"
                      value={formData.mileage}
                      onChange={handleChange}
                      variant="outlined"
                      inputProps={{ min: 0 }}
                    />
                  </Grid>
                </Grid>

                {/* 状态信息 */}
                <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                  状态信息
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="注册日期"
                      name="registrationDate"
                      type="date"
                      value={formData.registrationDate}
                      onChange={handleChange}
                      required
                      variant="outlined"
                      InputLabelProps={{ shrink: true }}
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="保险到期日"
                      name="insuranceExpiry"
                      type="date"
                      value={formData.insuranceExpiry}
                      onChange={handleChange}
                      required
                      variant="outlined"
                      InputLabelProps={{ shrink: true }}
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="最后保养日期"
                      name="lastMaintenance"
                      type="date"
                      value={formData.lastMaintenance}
                      onChange={handleChange}
                      required
                      variant="outlined"
                      InputLabelProps={{ shrink: true }}
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="下次保养日期"
                      name="nextMaintenanceDate"
                      type="date"
                      value={formData.nextMaintenanceDate}
                      onChange={handleChange}
                      variant="outlined"
                      InputLabelProps={{ shrink: true }}
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <FormControl fullWidth>
                      <InputLabel>车辆状态</InputLabel>
                      <Select
                        name="status"
                        value={formData.status}
                        onChange={handleChange}
                        label="车辆状态"
                      >
                        {statuses.map(status => (
                          <MenuItem key={status.value} value={status.value}>{status.label}</MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  </Grid>
                </Grid>

                {/* 车主信息（已自动获取当前登录用户信息） */}
                <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                  车主信息
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="车主姓名"
                      name="ownerNameDisplay"
                      value={currentUser ? `${currentUser.firstName} ${currentUser.lastName}` : '加载中...'}
                      disabled
                      variant="outlined"
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="邮箱地址"
                      name="ownerEmailDisplay"
                      value={currentUser?.email || '加载中...'}
                      disabled
                      variant="outlined"
                    />
                  </Grid>
                </Grid>
                <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                  系统自动使用当前登录用户作为车主，如需修改请联系管理员。
                </Typography>

                {/* 设备信息 */}
                <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                  设备信息
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="设备ID"
                      name="deviceId"
                      value={formData.deviceId}
                      onChange={handleChange}
                      variant="outlined"
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="设备序列号"
                      name="deviceSerialNumber"
                      value={formData.deviceSerialNumber}
                      onChange={handleChange}
                      variant="outlined"
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="设备型号"
                      name="deviceModel"
                      value={formData.deviceModel}
                      onChange={handleChange}
                      variant="outlined"
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="设备版本"
                      name="deviceVersion"
                      value={formData.deviceVersion}
                      onChange={handleChange}
                      variant="outlined"
                    />
                  </Grid>
                </Grid>

                {/* 证件信息 */}
                <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                  证件信息
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="行驶证号"
                      name="registrationNumber"
                      value={formData.registrationNumber}
                      onChange={handleChange}
                      variant="outlined"
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="保险单号"
                      name="insurancePolicyNumber"
                      value={formData.insurancePolicyNumber}
                      onChange={handleChange}
                      variant="outlined"
                    />
                  </Grid>
                </Grid>

                {/* 位置信息 */}
                <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                  位置信息
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="纬度"
                      name="lastLatitude"
                      type="number"
                      value={formData.lastLatitude}
                      onChange={handleChange}
                      variant="outlined"
                      inputProps={{ step: 0.0001 }}
                    />
                  </Grid>
                  
                  <Grid item xs={12} sm={6}>
                    <TextField
                      fullWidth
                      label="经度"
                      name="lastLongitude"
                      type="number"
                      value={formData.lastLongitude}
                      onChange={handleChange}
                      variant="outlined"
                      inputProps={{ step: 0.0001 }}
                    />
                  </Grid>
                </Grid>

                {/* 安全设备 */}
                <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                  安全设备
                </Typography>
                <FormGroup row>
                  <FormControlLabel
                    control={<Checkbox checked={formData.hasGPS} onChange={handleChange} name="hasGPS" />}
                    label="GPS定位"
                  />
                  <FormControlLabel
                    control={<Checkbox checked={formData.hasAlarm} onChange={handleChange} name="hasAlarm" />}
                    label="报警器"
                  />
                  <FormControlLabel
                    control={<Checkbox checked={formData.hasImmobilizer} onChange={handleChange} name="hasImmobilizer" />}
                    label="防盗器"
                  />
                  <FormControlLabel
                    control={<Checkbox checked={formData.hasCamera} onChange={handleChange} name="hasCamera" />}
                    label="摄像头"
                  />
                </FormGroup>

                {/* 标签和备注 */}
                <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                  标签和备注
                </Typography>
                <Grid container spacing={3}>
                  <Grid item xs={12}>
                    <TextField
                      fullWidth
                      label="添加标签"
                      value={tagInput}
                      onChange={(e) => setTagInput(e.target.value)}
                      onKeyPress={handleKeyPress}
                      variant="outlined"
                      helperText="输入标签后按回车添加"
                    />
                    <Box sx={{ mt: 1 }}>
                      {formData.tags.map((tag, index) => (
                        <Chip
                          key={index}
                          label={tag}
                          onDelete={() => handleTagDelete(tag)}
                          color="primary"
                          variant="outlined"
                          sx={{ mr: 1, mb: 1 }}
                        />
                      ))}
                    </Box>
                  </Grid>
                  
                  <Grid item xs={12}>
                    <TextField
                      fullWidth
                      label="备注"
                      name="notes"
                      value={formData.notes}
                      onChange={handleChange}
                      variant="outlined"
                      multiline
                      rows={3}
                    />
                  </Grid>
                </Grid>

                <Grid item xs={12} sx={{ mt: 3 }}>
                  <Button
                    type="submit"
                    variant="contained"
                    color="primary"
                    size="large"
                    fullWidth
                    disabled={loading}
                    startIcon={<AddIcon />}
                  >
                    {loading ? <CircularProgress size={24} /> : '添加车辆'}
                  </Button>
                </Grid>
              </form>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={4}>
          <Paper elevation={3} sx={{ p: 2 }}>
            <Typography variant="h6" gutterBottom>
              填写说明
            </Typography>
            <Typography variant="body2" color="textSecondary" paragraph>
              请准确填写车辆信息，所有字段均为必填项。
            </Typography>
            <Typography variant="body2" color="textSecondary" paragraph>
              <strong>VIN码：</strong>17位车辆识别号码
            </Typography>
            <Typography variant="body2" color="textSecondary" paragraph>
              <strong>车牌号：</strong>按照实际车牌填写，如：京A12345
            </Typography>
            <Typography variant="body2" color="textSecondary" paragraph>
              <strong>发动机号：</strong>车辆发动机上的唯一标识
            </Typography>
          </Paper>
        </Grid>
      </Grid>
    </Box>
  );
};

export default AddVehicle;